<template>
  <div>
    <div>
      <div>
        <BasicTable @register="registerTable">
          <template #tableTitle>
            <Icon icon="ant-design:align-left-outlined" class="m-1 pr-1" />
            <span> 待开票区 {{ getTitle.value }}</span>
          </template>
          <template #toolbar>
            <a-button
              type="primary"
              @click="handleBatchAdd({})"
              v-auth="'shop:order:cusFpApply:edit'"
            >
              <Icon icon="fluent:add-12-filled" /> {{ t('批量添加') }}
            </a-button>
          </template>
        </BasicTable>
      </div>
      <div>
        <BasicTable @register="registerTable2">
          <template #tableTitle>
            <Icon icon="ant-design:align-right-outlined" class="m-1 pr-1" />
            <span> 待确认区 </span>
          </template>
          <template #toolbar>
            <a-popconfirm
              title="是否确认开票"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handleComfirmSel()"
            >
              <a-button type="success" v-auth="'shop:order:cusFpApply:edit'">
                <Icon icon="ant-design:check-outlined" /> {{ t('确认开票') }}
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              title="是否确认清除选中数据？"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handleDeleteSel()"
            >
              <a-button type="warning" v-auth="'shop:order:cusFpApply:edit'">
                <Icon icon="ant-design:delete-outlined" /> {{ t('清除选中待确认数据') }}
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              title="是否确认清除所有待确认数据？"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handleClearAllSel()"
            >
              <a-button type="error" v-auth="'shop:order:cusFpApply:edit'">
                <Icon icon="ant-design:delete-outlined" /> {{ t('清除所有待确认数据') }}
              </a-button>
            </a-popconfirm>
          </template>
        </BasicTable>
        <InputForm @register="registerDrawer" @success="handleSuccess2" />

        <InputForm2 @register="registerDrawer2" @success="handleSuccess2" />
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderCusFpApplyListKpSel',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, watch, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { cusFpApplyKpListData, cusFpApplyAddToSel, cusFpApplyComfirmSel } from '/@/api/shop/order/cusFpApply';
  import {
    cusFpApplySelSeledListData,
    cusFpApplySelDeleteByUser,
    cusFpApplySelDelete,
  } from '/@/api/shop/order/cusFpApplySel';
  import { useDrawer } from '/@/components/Drawer';
  import { BpmRuntimeTrace } from '/@/components/Bpm';
  import { FormProps } from '/@/components/Form';
  import { useModal, BasicModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import InputForm from '../cusFpApplySel/form.vue';

  import InputForm2 from './form.vue';

  const { t } = useI18n('shop.order.cusFpApply');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.query.cusName,
  };
  watch(
    () => router.currentRoute.value.query.cusCode,
    () => {},
  );

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('订单号'),
        field: 'soMain.code',
        component: 'Input',
        show: true,
      },
      // {
      //   label: t('订单日期'),
      //   field: 'soMain.ddate',
      //   // component: 'RangePicker',
      //   component: 'DatePicker',
        
      // },

      {
        label: t('存货编码'),
        field: 'basInv.cinvcode',
        component: 'Input',
      },
      {
        label: t('存货名称'),
        field: 'basInv.cinvname',
        component: 'Input',
      },
      {
        label: t('规格型号'),
        field: 'basInv.cinvstd',
        component: 'Input',
      },
      
    ],
    // fieldMapToTime: [
    //   ['createDate', ['createDate_gte', 'createDate_lte']],
    //   ['overDate', ['overDate_gte', 'overDate_lte']],
    // ],
  };

  const searchForm2: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      // applyRds.
    {
        label: t('订单号'),
        field: 'soMain.code',
        component: 'Input',
        show: true,
      },
      {
        label: t('存货编码'),
        field: 'basInv.cinvcode',
        component: 'Input',
      },
      {
        label: t('存货名称'),
        field: 'basInv.cinvname',
        component: 'Input',
      },
      {
        label: t('规格型号'),
        field: 'basInv.cinvstd',
        component: 'Input',
      },
    ],
    fieldMapToTime: [
      ['createDate', ['createDate_gte', 'createDate_lte']],
      ['overDate', ['overDate_gte', 'overDate_lte']],
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('订单号'),
      dataIndex: 'soMain.code',
      key: 'a.order_code',
      sorter: true,
      width: 150,
      align: 'center',
    },
    {
      title: t('订单日期'),
      dataIndex: 'soMain.ddate',
      key: 'soMain.ddate',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('存货编码'),
      dataIndex: 'basInv.cinvcode',
      key: 'a.inv_code',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'basInv.cinvname',
      key: 'inv.cinvname',
      sorter: true,
      width: 180,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      key: 'inv.cinvstd',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'basInv.unitName',
      key: 'inv.unit_name',
      sorter: true,
      width: 70,
      align: 'left',
    },
    {
      title: t('销售数量'),
      dataIndex: 'soRds.iquantity',
      key: 'a.iquantity',
      sorter: true,
      width: 120,
      align: 'center',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      key: 'a.itaxunitprice',
      sorter: false,
      width: 120,
      align: 'right',
    },
    {
      title: t('销售金额'),
      dataIndex: 'soRds.isum',
      key: 'a.isum',
      sorter: true,
      width: 120,
      align: 'center',
    },
    {
      title: t('折扣额'),
      dataIndex: 'soRds.isum',
      key: 'a.isum',
      sorter: true,
      width: 80,
      align: 'center',
    },
    {
      title: t('已开数量'),
      dataIndex: 'soRds.kpQty',
      key: 'a.kp_qty',
      sorter: false,
      width: 120,
      align: 'center',
    },
    {
      title: t('已开金额'),
      dataIndex: 'soRds.kpSum',
      key: 'a.isum',
      sorter: false,
      width: 120,
      align: 'center',
    },

    {
      title: t('已开折扣'),
      dataIndex: 'soRds.kpSaleSum',
      key: 'a.kp_sale_sum',
      sorter: false,
      width: 120,
      align: 'center',
    },
    {
      title: t('剩余数量'),
      dataIndex: 'sykpQty',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('剩余金额'),
      dataIndex: 'sykpSum',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('剩余折扣'),
      dataIndex: 'sykpSaleSum',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
  ];
  const tableColumns2: BasicColumn[] = [
    {
      title: t('订单号'),
      dataIndex: 'applyRds.soMain.code',
      key: 'a.order_code',
      sorter: false,
      width: 150,
      align: 'center',
    },
    {
      title: t('订单日期'),
      dataIndex: 'applyRds.soMain.ddate',
      key: 'soMain.ddate',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('存货编码'),
      dataIndex: 'applyRds.basInv.cinvcode',
      key: 'a.inv_code',
      sorter: false,
      width: 120,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'applyRds.basInv.cinvname',
      key: 'inv.cinvname',
      sorter: false,
      width: 180,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'applyRds.basInv.cinvstd',
      key: 'inv.cinvstd',
      sorter: false,
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'applyRds.basInv.unitName',
      key: 'inv.unit_name',
      sorter: false,
      width: 70,
      align: 'left',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      key: 'iprice',
      sorter: false,
      width: 80,
      align: 'right',
    },
    {
      title: t('剩余数量'),
      dataIndex: 'applyRds.sykpQty',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('剩余金额'),
      dataIndex: 'applyRds.sykpSum',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('剩余折扣'),
      dataIndex: 'applyRds.sykpSaleSum',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('本次数量'),
      dataIndex: 'iqty',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('本次金额'),
      dataIndex: 'isum',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('本次折扣'),
      dataIndex: 'saleSum',
      sorter: false,
      width: 200,
      align: 'center',
      fixed: 'right',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'fluent:add-12-filled',
        color: 'success',
        title: t('添加至待确认区'),
        onClick: handleAdd.bind(this, { id: record.sodid }),
        auth: 'shop:order:cusFpApply:edit',
      },
    ],
  };
  const actionColumn2: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑待确认记录'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'shop:order:cusFpApply:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除待确认记录'),
        popConfirm: {
          title: t('是否确认删除待确认记录'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'shop:order:cusFpApply:edit',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawer2, { openDrawer: openDrawer2}] = useDrawer();

  
  const [registerTable, { reload, getSelectRows }] = useTable({
    api: cusFpApplyKpListData,
    beforeFetch: (params) => {
      params.cusCode = router.currentRoute.value.query.cusCode;
      console.log(params);
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowSelection: {
      type: 'checkbox',
    },
    rowKey: 'sodid',
    tableSetting: { fullScreen: true },
    // isCanResizeParent: true,
     scroll: {
      y: 300,
    },
  });
  const [registerTable2, { reload: reload2, getSelectRows: getSelectRows2 }] = useTable({
    api: cusFpApplySelSeledListData,
    beforeFetch: (params) => {
      params.cusCode = router.currentRoute.value.query.cusCode;
      console.log(params);
      return params;
    },
    columns: tableColumns2,
    actionColumn: actionColumn2,
    formConfig: searchForm2,
    showTableSetting: true,
    useSearchForm: true,
    showSearchForm: false,
    canResize: true,
    resizeHeightOffset:55,
    rowSelection: {
      type: 'checkbox',
    },
    rowKey: 'sodid',
    tableSetting: { fullScreen: true },
    // isCanResizeParent: true,
    pagination: false,
    showSummary: true,
    summaryFunc: handleSummary,
  });
  function handleSummary(tableData: Recordable[]) {
    const sykpQty = tableData.reduce((prev, next) => {
      prev += next.applyRds.sykpQty ? next.applyRds.sykpQty : 0;
      return prev;
    }, 0);

    const sykpSum = tableData.reduce((prev, next) => {
      prev += next.applyRds.sykpSum ? next.applyRds.sykpSum : 0;
      return prev;
    }, 0);

    const sykpSaleSum = tableData.reduce((prev, next) => {
      prev += next.applyRds.sykpSaleSum ? next.applyRds.sykpSaleSum : 0;
      return prev;
    }, 0);

    const iqty = tableData.reduce((prev, next) => {
      prev += next.iqty ? next.iqty : 0;
      return prev;
    }, 0);
    const isum = tableData.reduce((prev, next) => {
      prev += next.isum ? next.isum : 0;
      return prev;
    }, 0);

    const saleSum = tableData.reduce((prev, next) => {
      prev += next.saleSum ? next.saleSum : 0;
      return prev;
    }, 0);

    const zkl = ((saleSum / isum)* 100).toFixed(2)


    return [
      {
        _row: '合计',
        // _index: '折扣率',
        // 'applyRds.sykpQty': sykpQty,
        // 'applyRds.sykpSum': sykpSum,
        // 'applyRds.sykpSaleSum': sykpSaleSum,
        'applyRds':{
          sykpQty,
          sykpSum,
          sykpSaleSum,
        },
        'iqty': iqty,
        'isum': isum,
        'saleSum': saleSum + `（折扣率:${zkl}%）` ,

      },
    ];
  }
  //添加至待确认区
  async function handleAdd(record: Recordable) {
    const res = await cusFpApplyAddToSel({ selIds: record.id,cusCode:router.currentRoute.value.query.cusCode} );
    showMessage(res.message);
    handleSuccess();
  }
  //添加至待确认区（批量）
  async function handleBatchAdd() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.sodid + ',';
      });
      const res = await cusFpApplyAddToSel({ selIds: selIds.value,cusCode:router.currentRoute.value.query.cusCode});
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }
  async function handleClearAllSel() {
    const res = await cusFpApplySelDeleteByUser({cusCode:router.currentRoute.value.query.cusCode});
    showMessage(res.message);
    handleSuccess();
  }
  function handleSuccess() {
    reload();
    reload2();
  }
  function handleSuccess2() {
    reload2();
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const res = await cusFpApplySelDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleComfirmSel(){
    const res = await cusFpApplyComfirmSel({ cusCode:router.currentRoute.value.query.cusCode });
    showMessage(res.message);
    if(res.result == 'true'){
      handleSuccess2();
      openDrawer2(true, {id:res.data})
    }
  }
  async function handleDeleteSel() {
    if (getSelectRows2().length) {
      var selIds = ref('');
      getSelectRows2().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await cusFpApplySelDelete({ selIds: selIds.value });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
    handleSuccess();
  }
</script>
<style scoped>
</style>
